/*
 * WordBrowser.cpp
 *
 *  Created on: May 20, 2009
 *      Author: walter
 */

#include "WordBrowser.h"

BrowseForm::BrowseForm():
	id(-1),
	English(QString()),
	tip(QString()),
	EnglishFormat(QString()),
	historyType(HT_Search)
{
}

BrowseForm::BrowseForm(int i, QString e, QString t, QString ef, BrowseFormType h)
	:id(i),
	English(e),
	tip(t),
	EnglishFormat(ef),
	historyType(h)
{
}

BrowseForm::BrowseForm(const BrowseForm& b)
{
	id = b.id;
	English = b.English;
	tip = b.tip;
	EnglishFormat = b.EnglishFormat;
	historyType = b.historyType;
}

WordBrowser::WordBrowser(QWidget * parent):
	QWidget(parent),
	mNavListWidth(0.2f),
	mLastWordID(-1),
	mCurPageID(0),
	mTopItem(NULL),
	mArticleRootItem(NULL),
	mCurWord(NULL)
{
	ui.setupUi(this);
	mBrowseForm.clear();

	ui.homePageButton->setIcon(QIcon("./pixmaps/agt_home-256.png"));
	QObject::connect(ui.homePageButton, SIGNAL(clicked()), this, SLOT(goToHomePage()));
	goHomePageShortcut = new QShortcut(QKeySequence(Qt::Key_H),  this);
	QObject::connect(goHomePageShortcut, SIGNAL(activated()), ui.homePageButton, SIGNAL(clicked()));

	ui.nextPageButton->setIcon(QIcon("./pixmaps/next-256.png"));
	QObject::connect(ui.nextPageButton, SIGNAL(clicked()), this, SLOT(goToNextPage()));
	goNextPageShortcut = new QShortcut(QKeySequence(Qt::Key_M),  this);
	QObject::connect(goNextPageShortcut, SIGNAL(activated()), ui.nextPageButton, SIGNAL(clicked()));

	ui.previousPageButton->setIcon(QIcon("./pixmaps/previous-256.png"));
	QObject::connect(ui.previousPageButton, SIGNAL(clicked()), this, SLOT(goToPreviousPage()));
	goPreviousPageShortcut = new QShortcut(QKeySequence(Qt::Key_N),  this);
	QObject::connect(goPreviousPageShortcut, SIGNAL(activated()), ui.previousPageButton, SIGNAL(clicked()));

	scrollUpShortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_J),  this);
	QObject::connect(scrollUpShortcut,SIGNAL(activated()),this,SLOT(browserScrollUp()));
	QObject::connect(new QShortcut(QKeySequence(Qt::Key_J),  this)
							,SIGNAL(activated()),this,SLOT(browserScrollUp()));

	scrollDownShortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_K),  this);
	QObject::connect(scrollDownShortcut,SIGNAL(activated()),this,SLOT(browserScrollDown()));
	QObject::connect(new QShortcut(QKeySequence(Qt::Key_K),  this)
								,SIGNAL(activated()),this,SLOT(browserScrollDown()));

	showSearchBarShortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_F),  this);
	QObject::connect(showSearchBarShortcut,SIGNAL(activated()),this,SLOT(showSearchBar()));
	QObject::connect(showSearchBarShortcut,SIGNAL(activated()),ui.searchWordEdit,SLOT(setFocus()));

	hideSearchBarShortcut = new QShortcut(QKeySequence(Qt::Key_Escape),  this);
	QObject::connect(hideSearchBarShortcut,SIGNAL(activated()),this,SLOT(hideSearchBar()));

	searchWordAction = new QAction(tr("Find Word"), this);
	searchWordAction->setShortcut(QKeySequence(Qt::Key_Return));
	QObject::connect(searchWordAction,SIGNAL(activated()),this,SLOT(searchWord()));
	ui.searchWordButton->setDefaultAction(searchWordAction);
	ui.searchWordButton->setIcon(QIcon("./pixmaps/find-256.png"));
	ui.searchWordEdit->setFont(this->font());
	ui.searchWordEdit->hide();
	ui.searchWordButton->hide();

	//speak
	ui.speakButton->setIcon(QIcon("./pixmaps/speaker.png"));
	QObject::connect(ui.speakButton, SIGNAL(clicked()), this, SLOT(speak()));
	speakButtonClickedShortcut = new QShortcut(QKeySequence(Qt::Key_S),  this);
	QObject::connect(speakButtonClickedShortcut,SIGNAL(activated()),this,SLOT(speak()));

	//adjust splitter
	int width = this->width();
	QList<int> sizes;
	sizes<<width*mNavListWidth<<width*(1.0f-mNavListWidth);
	ui.splitter->setSizes(sizes);

	//set navigator view
	//ui.wordNavTree->setWordWrap(true);
	ui.wordNavTree->setHeaderHidden(true);
	QObject::connect(ui.wordNavTree, SIGNAL(itemClicked(QTreeWidgetItem*, int)), this, SLOT(itemActivated(QTreeWidgetItem*, int)));
	//QObject::connect(this, SIGNAL(itemActivatedSig(QTreeWidgetItem*, int)), this, SLOT(itemActivated(QTreeWidgetItem*, int)));
	QObject::connect(new QShortcut(QKeySequence(Qt::SHIFT + Qt::Key_J),  this)
									,SIGNAL(activated()),this,SLOT(activateNextItem()));
	QObject::connect(new QShortcut(QKeySequence(Qt::SHIFT + Qt::Key_K),  this)
									,SIGNAL(activated()),this,SLOT(activatePreviousItem()));
	//QObject::connect(new QShortcut(QKeySequence(Qt::Key_Return),  this)
	//								,SIGNAL(activated()),this,SLOT(enterKeyPressed()));

	ui.wordNavTree->setIndentation(10);
	hideArticleNav();
}

WordBrowser::~WordBrowser()
{
}

void WordBrowser::reset()
{
	mBrowseForm.clear();
}

void WordBrowser::hideArticleNav()
{
	ui.speakButton->hide();
	ui.wordNavTree->hide();
	//OPT.enableArticleNav = false;
	OPT.lockArticleNav = true;

	int width = this->width();
	QList<int> sizes;
	sizes<<0<<width;
	ui.splitter->setSizes(sizes);
}

void WordBrowser::showNavList()
{
	if (OPT.enableArticleNav && !OPT.lockArticleNav)
	{
		ui.speakButton->show();
		ui.wordNavTree->setFont(ui.wordBrowserDisplay->font());
		ui.wordNavTree->show();
		//OPT.enableArticleNav = true;

		int width = this->width();
		QList<int> sizes;
		sizes<<width*mNavListWidth<<width*(1.0f-mNavListWidth);
		ui.splitter->setSizes(sizes);
	}
}

void WordBrowser::setNavList()
{
	mTopItem->setText(0, QString("TOP"));
	//for (int i=0; i<ui.wordNavTree->topLevelItemCount(); i++)
	//	ui.wordNavTree->takeTopLevelItem(i);
	ui.wordNavTree->setFont(ui.wordBrowserDisplay->font());
	ui.wordNavTree->addTopLevelItem(mTopItem);
	ui.wordNavTree->addTopLevelItem(mArticleRootItem);
	//ui.wordNavTree->addTopLevelItem(&mThesaurusRootItem);
	ui.wordNavTree->expandAll();
}

void WordBrowser::itemActivated(QTreeWidgetItem* item, int column)
{
	map<QTreeWidgetItem*, int>::iterator it_it = mNavItemListMap.find(item);
	if (it_it != mNavItemListMap.end())
	{
		ui.wordNavTree->scrollToItem(item);
		if (mCurItem != mNavItemListVector.indexOf(item))
			mCurItem = mNavItemListVector.indexOf(item);

		if (mNavItemListMap[item] >= 0 )
		{
			//cout<<"WordBrowser::itemActivated-->item="<<item->text(0).toUtf8().data()<<endl;
			//cout<<"WordBrowser::itemActivated-->item.parent="<<item->parent()->text(0).toUtf8().data()<<endl;
			//set backgroud color
			QString content = mHtml;
			//content.replace("<FONT style=\"BACKGROUND-COLOR: #ccff66", "<FONT style=\"BACKGROUND-COLOR: #ffffff");
			int pos = content.indexOf(QString("<!--item[%1]-->").arg(mCurItem));
			if (pos != -1)
			{
				pos += (QString("<!--item[%1]--><FONT style=\"BACKGROUND-COLOR: ").arg(mCurItem).size());
				content.replace(pos, OPT.mainShadingColor.size(), OPT.selectShadingColor);
			}
			//cout<<"WordBrowser::itemActivated-->content="<<content.toUtf8().data()<<endl;
			ui.wordBrowserDisplay->clear();
			ui.wordBrowserDisplay->insertHtml(content);

			//move scroll bar
			/*if (item->parent())
			{
				cout<<"WordBrowser::itemActivated-->item.parent="<<item->parent()->text(0).toUtf8().data()<<endl;
				if (ui.wordBrowserDisplay->find(item->parent()->text(0)))
					cout<<"WordBrowser::itemActivated-->"<<item->parent()->text(0).toUtf8().data()<<" found."<<endl;
			}*/

			QTextCursor cursor = ui.wordBrowserDisplay->textCursor();
			cursor.setPosition(mNavItemListMap[item]);
			int buttonLine = ui.wordBrowserDisplay->verticalScrollBar()->maximumHeight();
			ui.wordBrowserDisplay->verticalScrollBar()->setValue(buttonLine);
			ui.wordBrowserDisplay->setTextCursor(cursor);
		}
	}
}

void WordBrowser::activateNextItem()
{
	//cout<<"WordBrowser::activateNextItem"<<endl;
	if (OPT.enableArticleNav && !OPT.lockArticleNav)
	{
		for (int i=0; i<mNavItemListVector.size(); i++)
			mNavItemListVector[i]->setSelected(false);

		mCurItem++;
		mCurItem=mCurItem%(mNavItemListVector.size());
		mNavItemListVector[mCurItem]->setSelected(true);
		//emit itemActivatedSig(mNavItemListVector[mCurItem], 0);
		itemActivated(mNavItemListVector[mCurItem], 0);
	}
}

void WordBrowser::activatePreviousItem()
{
	if (OPT.enableArticleNav && !OPT.lockArticleNav)
	{
		//cout<<"WordBrowser::activateNextItem"<<endl;
		for (int i=0; i<mNavItemListVector.size(); i++)
			mNavItemListVector[i]->setSelected(false);

		mCurItem += mNavItemListVector.size();
		mCurItem--;
		mCurItem=mCurItem%(mNavItemListVector.size());
		mNavItemListVector[mCurItem]->setSelected(true);
		//emit itemActivatedSig(mNavItemListVector[mCurItem], 0);
		itemActivated(mNavItemListVector[mCurItem], 0);
	}
}

void WordBrowser::showAll(BrowseForm& history, bool record)
{
	int id = history.id;
	QString English = history.English;
	QString EnglishFormat = history.EnglishFormat;
	clearDisplay();
	if (id == -1)
	{
		id = WM.getCurWordID();
		history.id = id;
	}

	if (id > 0)
	{
		English = WM.getWord(id)->getEnglish();
		history.English = English;
	}

	if (record && (id != mLastWordID || English != mLastEnglish))
	{

		if (id > 0)
			mLastEnglish = WM.getWord(id)->getEnglish();
		else if (id == -2 && !English.isEmpty())
			mLastEnglish = English;
		else
		{
			cout<<"WordBrowser::showAll-->Illegal BrowseForm. Unexpected id("<<id<<")"<<endl;
			//assert(0);
			return;
		}

		mLastWordID = id;
		mBrowseForm.push_back(history);
		mCurPageID = mBrowseForm.size()-1;
	}

	showEnglish(id, EnglishFormat);
	showSoundMark();
	showAllExplanations();
}

void WordBrowser::showHistory(int pageID)
{
	if (pageID < 0 || pageID >= mBrowseForm.size())
	{
		cout<<"WordBrowser::showHistory-->invalid pageID("<<pageID<<")\tmBrowseForm.size()="<<mBrowseForm.size()<<endl;
		assert(0);
	}

	int id=mBrowseForm[pageID].id;
	QString tip=mBrowseForm[pageID].tip;
	QString English = mBrowseForm[pageID].English;
	QString EnglishFormat = mBrowseForm[pageID].EnglishFormat;
	BrowseFormType type = mBrowseForm[pageID].historyType;

	if (type == HT_Test || type == HT_Browse)
	{
		clearDisplay();
		insertHtml(QString("History Page:%1 ").arg(pageID) + tip + QString("<BR><HR><BR>"));
		showEnglish(id, EnglishFormat);
		showSoundMark();
		showAllExplanations();
	}
	else if (type == HT_Search)
	{
		mCurWord = new Word();
		mCurWord->setEnglish(English);
		DM.lookup(mCurWord);
		clearDisplay();
		insertHtml(QString("History Page:%1 ").arg(pageID) + tip + QString("<BR><HR><BR>"));
		showEnglish(id, EnglishFormat);
		showSoundMark();
		showAllExplanations();
		//QString tip = QString("<FONT COLOR='BLUE'>SEARCH</FONT>");
		//tip.prepend(QString("History Page:%1 ").arg(pageID));
		//tip.append(QString("<BR><HR><BR>"));
		//QString EnglishFormat = QString("<FONT SIZE=5>%1</FONT><BR>");
		//BrowseForm history(-2, English, tip, EnglishFormat, HT_Search);
		//showAll(history, false);
		delete mCurWord;
		mCurWord = NULL;
	}
	else
	{
		cout<<"WordBrowser::showHistory-->invalid history item."<<endl;
		assert(0);
	}

	/*if (id > 0)
	{

	}


	else if (id == -2 && !English.isEmpty())
	{
		clearDisplay();
		insertHtml(QString("History Page:%1 ").arg(pageID) + tip + QString("<BR><HR><BR>"));
		mCurWord = new Word();
		mCurWord->setEnglish(English);
		DM.lookup(mCurWord);
		showEnglish(-2, EnglishFormat);
		showSoundMark();
		showAllExplanations();
		//showAll(QString("<FONT COLOR='BLUE'>SEARCH<FONT>"), true, -2);
		delete mCurWord;
		mCurWord = NULL;
	}
	else
	{

	}*/
}

void WordBrowser::showEnglish(int id, QString format)
{
	cout<<"WordBrowser::showEnglish"<<endl;
	if (id >= -1)
	{
		if (id == -1)
			mCurWord = WM.getCurWord();
		else if (id > 0)
			mCurWord = WM.getWord(id);
	}

	if(mCurWord)
	{
		QString comment = QString("<!--[English]-->");
		QString English = mCurWord->getEnglish();
		//WLOG<<"WordBrowser::showEnglish-->English="<<English.toUtf8().data()<<endl;
		if (format.isEmpty())
			insertHtml(comment+English + QString("<br>"));
		else
		{
			if (!format.contains("%1"))
			{
				cout<<"WordBrowser::showEnglish-->Unexpected format: "<<format.toUtf8().data()<<endl;
				insertHtml(comment+English + QString("<br>"));
			}
			else
			{
				 QString EnglishString = format.replace("%1", English);
				 EnglishString.prepend(comment);
				 //insertHtml(EnglishString + QString("<br>"));
				 insertHtml(EnglishString);
			}
		}
	}
	else
	{
		cout<<"WordBrowser::showEnglish-->Error! No word to show. id="<<id<<endl;
		//assert(0);
	}

	if (OPT.autoSpeak)
		speak();
}

void WordBrowser::showSoundMark()
{
	if(mCurWord)
	{
		QString soundMark = mCurWord->getSoundMark();
		if (!soundMark.isEmpty())
		{
			map<QChar, vector<int> > markPos;
			for (int i=soundMark.size()-1; i>=0; i--)
			{
				if (soundMark[i] == '0') soundMark.replace(i, 1, "&#240;");
				if (soundMark[i] == '1') soundMark.replace(i, 1, "&#230;");
				if (soundMark[i] == '2') soundMark.replace(i, 1, "&#594;");
				if (soundMark[i] == '3') soundMark.replace(i, 1, "&#596;");
				if (soundMark[i] == '4') soundMark.replace(i, 1, "&#1241;");
				if (soundMark[i] == '5') soundMark.replace(i, 1, "&#643;");
				if (soundMark[i] == '6') soundMark.replace(i, 1, "&#331;");
				if (soundMark[i] == '7') soundMark.replace(i, 1, "&#952;");
				if (soundMark[i] == '8') soundMark.replace(i, 1, "&#652;");
				if (soundMark[i] == '9') soundMark.replace(i, 1, "&#658;");
				if (soundMark[i] == 'A') soundMark.replace(i, 1, "&#1108;");
				if (soundMark[i] == '\\') soundMark.replace(i, 1, "&#604;");
				//if (soundMark[i] == 'A') soundMark.replace(i, 1, "&#1108;");
				//if (soundMark[i] == '`') soundMark.replace(i, 1, "&#716");
				if (soundMark[i] == '`') soundMark.replace(i, 1, ",");
			}

			soundMark.prepend("[");
			soundMark.append("]<br>");
			QString comment = QString("<!--[SoundMark]-->");
			soundMark.prepend(comment);
			insertHtml(soundMark);
		}
	}
}

void WordBrowser::showAllExplanations()
{
	QString comment;
	if(mCurWord)
	{
		ui.wordNavTree->clear();
		mTopItem = new QTreeWidgetItem(ui.wordNavTree, QStringList("TOP"));
		mArticleRootItem = new QTreeWidgetItem();

		mCurItem = 0;
		//QList<QTreeWidgetItem *>arItems = mArticleRootItem->takeChildren();
		//for (int i=0; i<arItems.size(); i++)
		//	delete arItems[i];

		//QList<QTreeWidgetItem *>thItems = mThesaurusRootItem.takeChildren();
		//for (int i=0; i<thItems.size(); i++)
		//	delete thItems[i];

		mNavItemListMap.clear();
		mNavItemListVector.clear();

		mNavItemListVector.push_back(mTopItem);
		mNavItemListMap[mTopItem]=0;

		mArticleRootItem->setText(0, QString("Article for word \"%1\"").arg(mCurWord->getEnglish()));
		comment = QString("<!--[RedBible]-->");
		insertHtml(comment + mCurWord->getRedBibleExp() + QString("<br>"));

		QStringList queryDictList = DM.getQueryDictList();
		for (int i=0; i<queryDictList.size(); i++)
		{
			map<QString, QString>& articles = mCurWord->getExplanationMap(queryDictList[i]);
			if (articles.empty())
				continue;

			QTreeWidgetItem* dictItem = new QTreeWidgetItem(QStringList(queryDictList[i]));
			comment = QString("<!--Dict[%1]-->").arg(queryDictList[i]);
			insertHtml(comment);
			bool isValid = false;
			for (map<QString, QString>::iterator ar_it = articles.begin();
					ar_it != articles.end();
					ar_it++)
			{
				QString key = ar_it->first;
				if (!key.isEmpty())
				{
					QTreeWidgetItem* keyItem = new QTreeWidgetItem(QStringList(key));
					dictItem->addChild(keyItem);
					mNavItemListMap[keyItem]=ui.wordBrowserDisplay->textCursor().position();
					mNavItemListVector.push_back(keyItem);
					comment = QString("<!--Key[%1]-->").arg(key);
					insertHtml(comment);
					insertHtml(QString("<!--item[%1]-->").arg(mNavItemListVector.size()-1));
					insertHtml(QString("<FONT style=\"BACKGROUND-COLOR: %1\">").arg(OPT.mainShadingColor));
					insertHtml(ar_it->second);
					insertHtml("</FONT>");

					isValid = true;
				}
			}
			if (isValid)
			{
				//cout<<"isValid="<<isValid<<endl;
				mArticleRootItem->addChild(dictItem);
			}
			insertHtml("<BR>");

			//if (OPT.showThNavList)
			//	if (queryDictList[i].contains("Merriam-Webster Collegiate") && queryDictList[i].contains("Thesaurus")) //need to set thesaurus tree view
			//		setThesaurusList(mCurWord->getEnglish(), queryDictList[i]);
		}
	}

	setNavList();
}

void WordBrowser::insertHtml(QString html)
{
	ui.wordBrowserDisplay->insertHtml(html);
	mHtml.append(html);
}

void WordBrowser::clearDisplay()
{
	ui.wordBrowserDisplay->clear();
	mHtml.clear();
}

/*void WordBrowser::setThesaurusList(QString key, QString dictName)
{
	QStringList thesaurus = DM.quickLookupThesaurus(key, dictName);
	if (thesaurus.isEmpty())
		mThesaurusRootItem.setText(0, QString());
	else
		mThesaurusRootItem.setText(0, QString("Thesaurus for word \"%1\"").arg(key));

	//cout<<"WordBrowser::showAllExplanations-->thesaurus="<<thesaurus.toUtf8().data()<<endl;
	for (int j=0; j<thesaurus.size(); j += 2)
	{
		//cout<<"WordBrowser::setThesaurusList-->thesaurus["<<j<<"]="<<thesaurus[j].toUtf8().data()<<endl;
		//cout<<"WordBrowser::setThesaurusList-->thesaurus["<<j+1<<"]="<<thesaurus[j+1].toUtf8().data()<<endl;
		QString key = thesaurus[j];
		QString thListString = thesaurus[j+1];
		if (thListString.isEmpty())
			continue;

		bool isValid=false;
		QTreeWidgetItem* keyItem = new QTreeWidgetItem(QStringList(key));
		QStringList categoryList;
		if (thListString.contains('|'))
			categoryList = thListString.split('|');
		else
			categoryList<<thListString;
		for (int k=0; k<categoryList.size(); k++)
		{
			if (!categoryList[k].contains(':'))
			{
				cout<<"WordBrowser::setThesaurusList-->Unexpected categoryList:"<<categoryList[k].toUtf8().data()<<endl;
				//do something
			}
			QStringList subCategory = categoryList[k].split(':');
			QString categoryName = subCategory[0];
			if (categoryName == "Function")
				continue;

			if (subCategory.size() == 2)
			{
				//cout<<"WordBrowser::setThesaurusList-->categoryName-->"<<categoryName.toUtf8().data()<<endl;
				isValid = true;
				QTreeWidgetItem* categoryItem = new QTreeWidgetItem(QStringList(categoryName));
				QStringList thWords;
				if (subCategory[1].contains(','))
					thWords = subCategory[1].split(',');
				else
					thWords<<subCategory[1];

				if (thWords.size() == 0)
					continue;
				else
				{
					keyItem->addChild(categoryItem);
					for (int m=0; m<thWords.size(); m++)
					{
						//cout<<"WordBrowser::setThesaurusList-->thWords["<<m<<"]"<<thWords[m].toUtf8().data()<<endl;
						QString thWord = thWords[m];
						thWord = thWord.simplified();
						QTreeWidgetItem* wordItem = new QTreeWidgetItem(QStringList(thWord));
						categoryItem->addChild(wordItem);
						mNavItemListMap[wordItem]=-1;
						mNavItemListVector.push_back(wordItem);
					}
				}
			}
			else
			{
				cout<<"WordBrowser::setThesaurusList-->Unexpected subCategory.size()="<<subCategory.size()<<endl;
				//do something
			}
		}

		if (isValid)
			mThesaurusRootItem.addChild(keyItem);
		else
			delete keyItem;
	}
}*/

void WordBrowser::browserScrollUp()
{
	int curValue = ui.wordBrowserDisplay->verticalScrollBar()->value();
	curValue = curValue + ui.wordBrowserDisplay->verticalScrollBar()->singleStep()*3;
	if (curValue < 0) curValue=0;
	if (curValue > ui.wordBrowserDisplay->verticalScrollBar()->maximum()) curValue=ui.wordBrowserDisplay->verticalScrollBar()->maximum();
	//cout<<"WordBrowser::browserScrollUp-->curValue="<<curValue<<endl;
	ui.wordBrowserDisplay->verticalScrollBar()->setValue(curValue);
}

void WordBrowser::browserScrollDown()
{
	int curValue = ui.wordBrowserDisplay->verticalScrollBar()->value();
	curValue = curValue - ui.wordBrowserDisplay->verticalScrollBar()->singleStep()*3;
	if (curValue < 0) curValue=0;
	if (curValue > ui.wordBrowserDisplay->verticalScrollBar()->maximum()) curValue=ui.wordBrowserDisplay->verticalScrollBar()->maximum();
	//cout<<"WordBrowser::browserScrollDown-->curValue="<<curValue<<endl;
	ui.wordBrowserDisplay->verticalScrollBar()->setValue(curValue);
}

void WordBrowser::goToHomePage()
{
	if (OPT.enableHistoryNav && !OPT.lockHistoryNav)
	{
		//QVector<int>& testWordHistory = WM.getTestWordHistory();
		//ui.wordBrowserDisplay->clear();
		//clearDisplay();
		if (!mBrowseForm.empty())
		{
			mCurPageID = mBrowseForm.size()-1;
			showHistory(mCurPageID);
			//showAll(QString("<FONT COLOR='GREEN'>[HOME PAGE]</FONT>"), false);
			//showAll(QString(), false);
			//showEnglish();
			//showSoundMark();
			//showAllExplanations();
			//display();
		}
	}
}

void WordBrowser::goToNextPage()
{
	if (OPT.enableHistoryNav && !OPT.lockHistoryNav)
	{
		//ui.wordBrowserDisplay->clear();
		//clearDisplay();
		//QVector<int>& testWordHistory = WM.getTestWordHistory();
		if (!mBrowseForm.empty())
		{
			mCurPageID++;
			mCurPageID = mCurPageID%mBrowseForm.size();
			showHistory(mCurPageID);
			//int id = mBrowseForm[mCurPageID].id;
			//showAll(id, false);
			//QString title = QString("<FONT COLOR='GREEN'>History page (%1)</FONT><BR>").arg(mCurPageID);
			//ui.wordBrowserDisplay->insertHtml(title);
			//showEnglish(id);
			//showSoundMark();
			//showAllExplanations();
			//display();
		}
	}
}

void WordBrowser::goToPreviousPage()
{
	if (OPT.enableHistoryNav && !OPT.lockHistoryNav)
	{
		//QVector<int>& testWordHistory = WM.getTestWordHistory();
		//ui.wordBrowserDisplay->clear();
		//clearDisplay();
		if (!mBrowseForm.empty())
		{
			mCurPageID--;
			mCurPageID = (mCurPageID+mBrowseForm.size())%mBrowseForm.size();
			showHistory(mCurPageID);
			//int id = testWordHistory[mCurPageID];
			//QString title = QString("<FONT COLOR='GREEN'>History page (%1)</FONT><BR>").arg(mCurPageID);
			//ui.wordBrowserDisplay->insertHtml(title);
			//showEnglish(id);
			//showSoundMark();
			//showAllExplanations();
			//display();
		}
	}
}

void WordBrowser::speak()
{
	if (OPT.enableSpeak && !OPT.lockSpeak && mCurWord)
	{
		//start new mplayer process
		//QDir dir = QDir::current();
		//dir.cd("WyabdcRealPeopleTTS");
		QDir dir(OPT.speakLibPath);
		QString Word = mCurWord->getEnglish() + QString(".wav");
		//cout<<"WordBrowser::speak-->word="<<Word.toUtf8().data()<<endl;
		QString capital = Word.left(1);
		dir.cd(capital);

		//QSound::play(soundFileName);
		QString soundFileName = QDir::fromNativeSeparators(dir.absolutePath()) + QString("/") + Word;
		if (OPT.useQSound)
		{
			//QString soundFileName = dir.absolutePath() + "/WyabdcRealPeopleTTS/" + capital + "/" + Word;
			cout<<"soundFileName="<<soundFileName.toUtf8().data()<<endl;
			QSound::play(soundFileName);
		}
		else if (!OPT.playSoundCommand.isEmpty())
		{
		//For Linux
			//QString soundFileName = dir.absolutePath() + QDir::separator() + Word;
			QString program = OPT.playSoundCommand;
			QStringList arguments;
			arguments << soundFileName;

			QProcess *myProcess = new QProcess(this);
			myProcess->start(program, arguments);
		}
		else
			cout<<"WordBrowser::speak-->Invalid setting."<<endl;
	}
}

void WordBrowser::showSearchBar()
{
	//cout<<"WordBrowser::showSearchBar"<<endl;
	if (OPT.enableWordBrowserSearch && !OPT.lockWordBrowserSearch)
	{
		ui.searchWordEdit->show();
		ui.searchWordButton->show();
		ui.searchWordEdit->selectAll();
		ui.searchWordEdit->setEnabled(true);
	}
}

void WordBrowser::hideSearchBar()
{
	ui.searchWordEdit->hide();
	ui.searchWordButton->hide();
}

void WordBrowser::searchWord()
{
	if (OPT.enableWordBrowserSearch && !OPT.lockWordBrowserSearch)
	{
		ui.searchWordEdit->hide();
		ui.searchWordButton->hide();
		QString key = ui.searchWordEdit->text();
		key = key.simplified();
		if (!key.isEmpty())
		{
			mCurWord = new Word();
			mCurWord->setEnglish(key);
			DM.lookup(mCurWord);
			QString tip = QString("<FONT COLOR='BLUE'>SEARCH</FONT>");
			QString EnglishFormat = QString("<FONT SIZE=5>%1</FONT><BR>");
			BrowseForm history(-2, key, tip, EnglishFormat, HT_Search);
			showAll(history);
			delete mCurWord;
			mCurWord = NULL;
		}
	}
	//QString result = quickLookup(key);
	//showAll();
}

